#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：BroadviewCoss
@File    ：send_wxwork_msg.py.py
@IDE     ：PyCharm
@Author  ：kdly
@Date    ：2025/4/14 下午1:04
'''
import time
import json
import hmac
import base64
import hashlib
import requests
import logging

logger = logging.getLogger()
# 修改权限
logger.setLevel(logging.INFO)


def get_token(qy_id, robot_secret):
    try:
        response = requests.post(
            f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={qy_id}&corpsecret={robot_secret}')
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        if data['errcode'] != 0:
            logger.error(f"获取企业微信access_token失败：{data}")
            return False
        return response.json()['access_token']
    except requests.exceptions.RequestException as e:
        logger.error(f"获取企业微信access_token失败：{str(e)}")
        return False


def send_wxwork_message(robot_secret, qy_id, agent_id, to_user, alert_data):
    """
    向企业微信自建应用发送消息
    :param robot_secret: 企业微信自建应用 Secret
    :param qy_id: 企业微信 企业ID
    :param agent_id: 企业微信自建应用 AgentId
    :param to_user: 企业微信接收信息的人员 账号ID
    :param alert_data: 要发送的消息内容 alert_data = {
        "group": "测试组",
        "type": "进程监控",
        "name": "test",
        "obj": "nginx",
        "hostname": "127.0.0.1",
        "status": 0,
        "error": "Probe failed",
        "start_time": "2025-04-02 16:27:28",
        "end_time": "2025-04-02 16:30:13"
    }
    :return: API响应内容
    """
    # 构建消息内容
    if alert_data['status'] == 0:

        content = """BroadviewCoss告警信息\n"""
    else:
        content = """BroadviewCoss告警恢复\n"""

    content += f"""监控分组: {alert_data['group']}
监控类型: {alert_data['type']}
监控名称: {alert_data['name']}
监控对象: {alert_data['obj']}"""

    if alert_data['status'] == 0:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}"""
        else:
            content += f"""
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}"""

    else:
        if alert_data['hostname']:
            content += f"""
监控主机: {alert_data['hostname']}
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}
恢复时间: {alert_data['end_time']}"""

        else:
            content += f"""
详细信息: {alert_data['error']}
故障时间: {alert_data['start_time']}
恢复时间: {alert_data['end_time']}"""

    message = {
        "touser": to_user,
        "msgtype": "text",
        "agentid": agent_id,
        "text": {
            "content": content
        },
        "safe": 0
    }
    try:
        access_token = get_token(qy_id, robot_secret)
        header = {"Content-Type": "application/json"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        res = requests.post(url, json=message, headers=header)
        logger.info(f"企业微信应用机器人：{res.json()}")
        print(res.json())
    except requests.exceptions.RequestException as e:
        logger.error(f"发送企业微信应用机器人告警失败：{str(e)}")
        return False
    return True

if __name__ == '__main__':
    # get_token('ww86fb19eeda4b77a6', 'sItbwpeGFxsTeP5ZDeg7sAkc_lXfASU9G5GlRCWJ8MA')
    alert_data = {
        "group": "测试组",
        "type": "进程监控",
        "name": "test",
        "obj": "nginx",
        "hostname": "127.0.0.1",
        "status": 1,
        "error": "Probe failed",
        "start_time": "2025-04-02 16:27:28",
        "end_time": "2025-04-02 16:30:13"
    }
    send_wxwork_message('xxx',
                        'xxx', '1000002','xxx',alert_data)
